#include <iostream>
#include <assert.h>
#include <stdio.h>

// 字符串拷贝函数
char *my_strcpy(char *dest, char *sorc)
{
    assert(dest && sorc);

    char *p = dest;
    while (*dest++ = *sorc++)
    {
        ;
    }

    return p;
}

// 字符串追加
char *my_strcat(char *dest, const char *sorc)
{
    assert(dest && sorc);

    char *p = dest;
    // 找到dest的结尾
    while (*(++dest) != '\0')
    {
        ;
    }

    while (*dest++ = *sorc++)
    {
        ;
    }

    return p;
}

// 字符串比较
int my_strcmp(char *arr1, char *arr2)
{
    assert(arr1 && arr2);

    while (*arr1 == *arr2)
    {
        if (*arr1 == '\0')
            return 0;

        arr1++;
        arr2++;
    }

    return (*arr1 - *arr2);
}

char *my_strstr(const char *arr1, const char *arr2)
{
    assert(arr1 && arr2);

    const char *s1 = arr1;
    const char *s2 = arr2;
    const char *p = arr1;

    while (*p)
    {
        s1 = p;
        s2 = arr2;
        while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
        {
            s1++;
            s2++;
        }
        if (*s2 == '\0')
            ;
        return (char *)p;

        p++;
    }

    return nullptr;
}

int my_strlen(const char *arr1)
{
    if (*arr1 == '\0')
        return 0;

    return 1 + my_strlen(arr1 + 1);
}

void *my_memmove(void *dest, const void *sorc, size_t n)
{
    assert(dest && sorc);
    void *p = dest;
    if (dest < sorc)
    {
        // 从前往后拷贝
        while (n--)
        {
            *(char *)dest = *(char *)sorc;
            dest = (char *)dest + 1;
            sorc = (char *)sorc + 1;
        }
    }
    else
    {
        // 从后往前拷贝
        while (n--)
        {
            *((char *)dest + n) = *((char *)sorc + n);
        }
    }

    return p;
}

void *my_memcopy(void *dest, const void *sorc, size_t n)
{
    assert(dest && sorc);
    void *p = dest;
    while (n--)
    {
        *(char *)dest = *(char *)sorc;
        dest = (char *)dest + 1;
        sorc = (char *)sorc + 1;
    }

    return p;
}

void *my_memset(void *buff, char ch, size_t n)
{
    assert(buff);

    for (int i = 0; i < n; i++)
    {
        *((char *)buff + i) = ch;
    }

    return buff;
}

int main()
{
    char arr1[] = "avcdf";
    char arr2[20] = {0};
    my_strcpy(arr2, arr1);
    printf("%s\n", arr2);

    return 0;
}